import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { usePetStore } from '../stores/pet'

// 导入组件
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Pet from '../views/Pet.vue'
import Tasks from '../views/Tasks.vue'
import Profile from '../views/Profile.vue'

const router = createRouter({
  history: createWebHistory(),  // 不指定 base
  routes: [
    {
      path: '/',
      component: Home,
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      component: Login,
      meta: { guest: true }
    },    {
      path: '/register',
      component: Register,
      meta: { guest: true }
    },
    {
      path: '/pet',
      component: Pet,
      meta: { requiresAuth: true }
    },
    {
      path: '/tasks',
      component: Tasks,
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'profile',
      component: Profile,
      meta: { requiresAuth: true }
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const petStore = usePetStore()
  
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    next('/login')
    return
  }
  
  if (to.meta.guest && userStore.isAuthenticated) {
    next('/')
    return
  }

  // 如果用户已登录且正在访问首页，确保宠物状态是最新的
  if (userStore.isAuthenticated && to.path === '/') {
    try {
      await petStore.fetchPet()
    } catch (error) {
      console.error('Failed to fetch pet data:', error)
    }
  }
  
  next()
})

export default router
